import { Injectable } from '@nestjs/common';
import { CreateSubjectDto } from './dto/create-subject.dto';
import { UpdateSubjectDto } from './dto/update-subject.dto';
import { Repository } from 'typeorm';
import { Subject } from './entities/subject.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { PageSubjectDto } from './dto/page-subject.dto';
import { PageResult } from '../common/dto/common.page-result';

@Injectable()
export class SubjectService {
  constructor(
    @InjectRepository(Subject)
    private readonly subjectRepository: Repository<Subject>,
  ) { }

  async create(createSubjectDto: CreateSubjectDto) {
    await this.subjectRepository.save(createSubjectDto);
  }

  async findAll() {
    return await this.subjectRepository.find();
  }

  async findOne(id: number) {
    return await this.subjectRepository.findOne({ where: { id } })
  }

  async update(id: number, updateSubjectDto: UpdateSubjectDto) {
    await this.subjectRepository.update(id, updateSubjectDto);
  }

  async remove(id: number) {
    const subject = await this.subjectRepository.findOne({ where: { id } })
    if (subject) {
      this.subjectRepository.remove(subject);
    } else {
      throw new Error('科目不存在');
    }
  }

  async page(pageSubjectDto: PageSubjectDto) {
    const page = pageSubjectDto.page;
    const size = pageSubjectDto.size;
    const query = this.subjectRepository.createQueryBuilder('subject')
    if (pageSubjectDto.name) {
      query.andWhere('subject.name like :name', { name: `%${pageSubjectDto.name}%` })
    }
    if (pageSubjectDto.status) {
      query.andWhere('subject.status = :status', { status: pageSubjectDto.status })
    }
    if (pageSubjectDto.type) {
      query.andWhere('subject.type = :type', { type: pageSubjectDto.type })
    }

    const [list, total] = await query
      .skip((page - 1) * size)
      .take(size)
      .getManyAndCount()

    return new PageResult(page, size, total, list);
  }

  async changeStatus(id: number, status: number) {
    const subject = await this.subjectRepository.findOne({ where: { id } })
    if (subject) {
      subject.status = status;
      await this.subjectRepository.update(id, subject);
    } else {
      throw new Error('科目不存在');
    }
  }
}
